//
//  WBEmoticonKeyboard.swift
//  0829-Weibo
//
//  Created by 毕仲阳 on 16/9/9.
//  Copyright © 2016年 mycompany. All rights reserved.
//

import UIKit

private let WBEmoticonCollectionCellId = "WBEmoticonCollectionCellId"
class WBEmoticonKeyboard: UIView {

    override init(frame: CGRect) {
        super.init(frame: frame)
        self.setUI()
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    func setPageControl(index:IndexPath){
        pageControl.numberOfPages = WBEmoticonKeyboardViewModel.sharedModel.allEmoticons[index.section].count
        pageControl.currentPage = index.row
        pageControl.isHidden = index.section == 0
    }
    private func setUI()
    {
        //self.backgroundColor = UIColor.red
        self.backgroundColor = UIColor(patternImage: #imageLiteral(resourceName: "emoticon_keyboard_background"))
        self.addSubview(toolBar)
        self.addSubview(emoticonCollectionView)
        self.addSubview(pageControl)
        toolBar.snp_makeConstraints { (make)->Void in
            make.left.right.bottom.equalTo(self)
            make.height.equalTo(37)
        }
        emoticonCollectionView.snp_makeConstraints { (make)->Void in
            make.left.right.top.equalTo(self)
            make.bottom.equalTo(toolBar.snp_top)
        }
        pageControl.snp_makeConstraints { (make)->Void in
            make.centerX.equalTo(emoticonCollectionView.snp_centerX)
            make.bottom.equalTo(emoticonCollectionView)
        }
        // 主队列异步，其中的闭包会在主线程空闲的时候执行。
        // 主线程什么时候空闲呢？就是界面已经加载完成了
        DispatchQueue.main.async {
            // 将collectionView滚动到指定的组
            let indexPath = IndexPath(item: 0, section: 1)
            // 滚动到对应的组
            self.emoticonCollectionView.scrollToItem(at: indexPath, at: UICollectionViewScrollPosition.left, animated: false)
            self.toolBar.selectedIndex = indexPath
        }
        

    }
    override func layoutSubviews() {
        super.layoutSubviews()
        let layout = emoticonCollectionView.collectionViewLayout as! UICollectionViewFlowLayout
        layout.itemSize = emoticonCollectionView.frame.size
    }

    
    //MARK: -懒加载控件
    lazy var toolBar:WBEmoticonToolBar = {
        let bar = WBEmoticonToolBar()
        bar.emoticonTypeChangeClosure = {(type)->() in
            //print("按钮点击\(type)")
            let indexPath = IndexPath(item: 0, section: type.rawValue)
            self.emoticonCollectionView.scrollToItem(at: indexPath , at: UICollectionViewScrollPosition.left, animated: false)
            self.setPageControl(index:indexPath)
        }
        return bar
    }()
    internal lazy var emoticonCollectionView:UICollectionView = {
        let layout = UICollectionViewFlowLayout()
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        layout.scrollDirection = .horizontal
        let collectionV = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
        
        collectionV.dataSource = self
        collectionV.delegate = self
        collectionV.register(WBEmoticonCell.self, forCellWithReuseIdentifier: WBEmoticonCollectionCellId)
        collectionV.isPagingEnabled = true
        
        collectionV.showsVerticalScrollIndicator = false
        collectionV.showsHorizontalScrollIndicator = false
        
        collectionV.bounces = false
        
        return collectionV
    }()
    lazy var pageControl:UIPageControl = {
        let pageControl = UIPageControl()
        pageControl.isUserInteractionEnabled = true
        pageControl.setValue(UIImage(named:"compose_keyboard_dot_normal"), forKey: "_pageImage")
        pageControl.setValue(UIImage(named: "compose_keyboard_dot_selected"), forKey: "_currentPageImage")
        pageControl.numberOfPages = 4
        return pageControl
    }()
}

extension WBEmoticonKeyboard: UICollectionViewDataSource,UICollectionViewDelegate{
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return WBEmoticonKeyboardViewModel.sharedModel.allEmoticons.count
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        //return 10
        return WBEmoticonKeyboardViewModel.sharedModel.allEmoticons[section].count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: WBEmoticonCollectionCellId, for: indexPath) as! WBEmoticonCell
        
        //cell.backgroundColor = RandomColor
        cell.backgroundColor = UIColor.white
        cell.indexPath = indexPath
        cell.emoticons = WBEmoticonKeyboardViewModel.sharedModel.allEmoticons[indexPath.section][indexPath.item]
        return cell
    }
    
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let cells = emoticonCollectionView.visibleCells
        if cells.count == 2 {
            let firstCell = cells.first!
            let lastCell = cells.last!
            
            let screenRect = UIScreen.main.bounds
            let x = firstCell.center.x - scrollView.contentOffset.x
            let firstPoint = CGPoint(x: x, y: firstCell.center.y)
            let index:IndexPath
            if screenRect.contains(firstPoint){
                index = emoticonCollectionView.indexPath(for: firstCell)!
            }else{
                index = emoticonCollectionView.indexPath(for: lastCell)!
            }
            self.toolBar.selectedIndex = index
            self.setPageControl(index: index)
        }
    }
}
